package com.atguigu.lease.web.admin.custom.interception;

import com.atguigu.lease.common.context.LoginUser;
import com.atguigu.lease.common.context.LoginUserContext;
import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;


/**
 * @author 李俊伟
 * @date 2024/12/25 21:31
 */

@Component
public class AuthenticationInterceptor implements HandlerInterceptor {
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
//        System.out.println("拦截器生效了---------------------------");
        String access_token = request.getHeader("access_token");
        // 如果token为null
        if(access_token == null) {
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_AUTH);
        }else {
            // token是存在的，使用parseToken 验证token是否过期
            Claims claims = JwtUtil.parseToken(access_token);
            Long userId = claims.get("userId", Long.class);
            String username = claims.get("username", String.class);
            // 将 token 负载数据保存到请求域中
//            request.setAttribute("userId", userId);
            LoginUserContext.setLoginUser(new LoginUser(userId, username));
        }
        return true;
    }
}